﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace TK
{
    public partial class CustomSerializer
    {
        void writeIEnumerable(CustomSerializerState state, IEnumerable o, Type elementType)
        {
            var objID = state.writeHeader();

            var tempEnumerator = o.GetEnumerator();
            tempEnumerator.Reset();
            var items = new List<object>();
            while (tempEnumerator.MoveNext())
                items.Add(tempEnumerator.Current);

            state.writeInt32(items.Count);
            writeSingleTypeCollection(state, items, elementType);
            state.updateHeader(objID);
        }

        object readIEnumerable(CustomSerializerState state, Type type, Type ownerType, string propertyName)
        {
            var header = state.readHeader();
            var count = state.readInt32();

            var arg0 = type.GetGenericArguments()[0];
            var tempList = Array.CreateInstance(arg0, count);// Activator.CreateInstance(typeof(List<>).MakeGenericType(arg0));

            readSingleTypeCollection(state, tempList, arg0, ownerType, propertyName);
            var o = Activator.CreateInstance(type, new[] { tempList }, null);

            return o;
        }
    }
}